package com.lobov.utils;

import java.util.List;
import java.util.StringTokenizer;

import com.lobov.entities.ContainerOfSnips;
import com.lobov.entities.Matrix;
import com.lobov.entities.Snip;

/**
 * Компоновщик списков данных в кастомные структуры
 * 
 */
public class Composer {

	/**
	 * Фабричный метод создания матрицы из списка строк
	 * 
	 * @param listOfStrings
	 * @return
	 */
	public static Matrix getMatrix(List<String> listOfStrings) {

		String firstString = listOfStrings.get(0);
		StringTokenizer st = new StringTokenizer(firstString, " ");
		int xlength = st.countTokens();
		int ylength = listOfStrings.size();
		int numOfElements = xlength * ylength;
		double[] values = new double[numOfElements];
		int[] xs = new int[numOfElements];
		int[] ys = new int[numOfElements];

		int numOfElement = 0;
		int y = 0;

		for (String str : listOfStrings) {
			StringTokenizer strTokenizer = new StringTokenizer(str);

			int x = 0;

			while (strTokenizer.hasMoreElements()) {

				values[numOfElement] = Double.parseDouble(strTokenizer
						.nextToken(" "));
				xs[numOfElement] = x;
				ys[numOfElement] = y;
				x++;
				numOfElement++;
			}
			y++;
		}

		Matrix matrix = new Matrix(xlength, ylength);
		matrix.setValues(values);
		matrix.setXs(xs);
		matrix.setYs(ys);

		return matrix;
	}

	public static ContainerOfSnips getContainerOfSnips(List<Snip> snipsList)
			throws Exception {
		ContainerOfSnips containerOFSnips = new ContainerOfSnips(
				snipsList.size(), snipsList.get(0).getXlength());
		Snip[] snips = containerOFSnips.getSnips();
		int counter = 0;
		for (Snip snip : snipsList) {
			if (snip.getXlength() != containerOFSnips.getSnipsXLength()) {
				throw new Exception(
						"Все лоскуты в контейнере должны иметь одинаковую ширину!");
			}
			snips[counter] = snip;
			counter++;
		}
		return containerOFSnips;
	}

}
